<template >
  <el-card class="box-card">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" style="max-width: 600px">
      <el-form-item label="优惠券类型：">
        <el-select class="m-2" placeholder="全部" v-model="form.type">
          <el-option v-for="item in optionsType" :key="item.value" :value="item.value" :label="item.label"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="优惠券名称:" prop="name" style="width: 450px;">
        <el-input v-model="form.name" placeholder="请输入优惠券名称" />
      </el-form-item>
      <el-form-item label="适用平台:" prop="platform">
        <el-select v-model="form.platform" class="m-2" placeholder="全平台">
          <el-option v-for="item in optionsPlatform" :key="item.value" :value="item.value"
            :label="item.label"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="发行总量:" prop="publishCount" style="width: 450px;">
        <el-input v-model="form.publishCount" placeholder="只能输入正整数" />
      </el-form-item>
      <el-form-item label="面额:" prop="amount">
        <div class="mt-4">
          <el-input v-model="form.amount" placeholder="面值只能是数值,限2位小数" class="input-with-select" style="width: 300px;">
            <template #append>
              元
            </template>
          </el-input>
        </div>
      </el-form-item>
      <el-form-item label="每人限领:" prop="perLimit">
        <div class="mt-4">
          <el-input v-model="form.perLimit" placeholder="只能输入正整数" style="width: 350px;">
            <template #append>
              张
            </template>
          </el-input>
        </div>
      </el-form-item>
      <el-form-item label="使用门槛:" prop="minPoint">
        <div class="mt-4">
          <el-input style="width: 350px;" v-model="form.minPoint" placeholder="只能输入正整数" class="input-with-select">
            <template #prepend>
              满
            </template>
            <template #append>
              元可用
            </template>
          </el-input>
        </div>
      </el-form-item>
      <el-form-item label="领取日期:" prop="form">
        <el-date-picker v-model="form.enableTime" type="date" placeholder="选择日期" />
      </el-form-item>
      <el-form-item label="有效期:" style="width: 400;">
        <el-date-picker v-model="form.startTime" type="date" placeholder="选择日期"
          style="width:170px;padding-right:20px" />
        <span>至</span>
        <el-date-picker v-model="form.endTime" type="date" placeholder="选择日期" style="width: 170px;padding-left:20px" />
      </el-form-item>
      <el-form-item label="可使用商品:" prop="useType">
        <div>
          <el-radio-group v-model="form.useType">
            <el-radio-button value="0" :label="0" @click="choose = 0">
              全场通用
            </el-radio-button>
            <el-radio-button value="1" :label="1" @click="choose = 1">
              指定分类
            </el-radio-button>
            <el-radio-button value="2" :label="2" @click="choose = 2">
              指定商品
            </el-radio-button>
          </el-radio-group>
        </div>
      </el-form-item>
      <div v-if="choose == 1" style="padding-left:100px;padding-bottom:20px">
        <div style="padding-bottom:20px">
          <el-cascader v-model="treeValue" :props="treeProps" :options="getChildrenList" clearable placeholder="选择分类名称"
            width="200px" />
          <el-button @click="addToList">添加</el-button>
        </div>
        <div>
          <el-table row-class-name=“rowClassName” :data="need" border style="width: 100%">
            <el-table-column label="分类名称" width="350" align="center">
              <template #default="{ row }">
                <div>
                  {{ row.parentCategoryName }}>{{ row.productCategoryName }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" type="index" width="150" align="center">
              <template #default="scope">
                <el-button text type="primary" @click="delProductRelationList" size="small">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div v-if="choose == 2" style="padding-left:100px;padding-bottom:20px">
        <div style="padding-bottom:20px">
          <el-select v-model="value1" filterable remote reserve-keyword placeholder="商品名称或商品货号"
            :remote-method="remoteMethod" :loading="loading" width="200px">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <el-button @click="addProductRelationList">添加</el-button>
        </div>
        <div>
          <el-table border :data="form.productRelationList" style="width: 100%">
            <el-table-column label="商品名称" width="300" align="center">
              <template #default="{ row }">
                <div>
                  {{ row.productName }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="货号" width="100">
              <template #default="{ row }">
                {{ 'NO. ' + row.productSn }}
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template #default="{ row }">
                <el-button text type="primary" @click="delProductRelationList(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <el-form-item label="备注:">
        <el-input v-model="form.note" :rows="5" type="textarea" placeholder="请输入内容" />
      </el-form-item>
    </el-form>
    <div class="flex">
      <el-button type="primary" @click="submitFn">保存</el-button>
      <el-button>清空</el-button>
    </div>
  </el-card>
</template>
<script setup lang="ts">
import { addCoupon, getProductCategoryListWithChildren, SearchProductList } from './api'
import { reactive, ref } from 'vue'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { useRouter } from 'vue-router';
const addProductRelationList = () => {
  // console.log(value1.value);

  let arr = list.value.filter((item: IProductModel) => item.id === value1.value)
  //  console.log(arr);


  needTwo.value = form.productRelationList?.push({
    productName: arr[0].name,
    productId: arr[0].id,
    productSn: arr[0].productSn
  })
  // console.log(needTwo.value);

}
const delProductRelationList = (row: productRelationList) => {
  form.productRelationList = form.productRelationList?.filter(item => item !== row)
}
interface ListItem {
  value: number
  label: string
}
const value1 = ref<number>()
const testFirst = ref()
const options = ref<ListItem[]>([])
const list = ref<IProductModel[]>([])
const loading = ref(false)
const remoteMethod = (query: string) => {
  if (query) {
    loading.value = true
    setTimeout(() => {
      SearchProductList(query).then(res => {
        if (res.code === 200) {
          list.value = res.data
          loading.value = false
          options.value = list.value.map((item) => {
            return {
              value: item.id,
              label: item.name
            }
          })
        }
      })

    }, 200)
  } else {
    options.value = []
  }
}
// value.value = states.map((item) => {
//     return { productSn:`productSn${item}`,name:`name${item}`,value: `value:${item}`, label: `label:${item}` }
//   })
//校验
const choose = ref(0)
const PositiveInteger = (rule: any, value: string, cb: any) => {
  if (!/^[1-9]\d*$/.test(value)) {
    return cb(new Error("只能输入正整数"));
  } else {
    cb();
  }
};
const Denomination = (rule: any, value: string, cb: any) => {
  if (!/^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/.test(value)) {
    return cb(new Error("面值只能是数值,0.01-10000,限2位小数"));
  } else {
    cb();
  }
};
const rules = {
  name: [{ required: true, trigger: "blur", message: "请输入优惠券名称" }],
  publishCount: [{ validator: PositiveInteger, required: true, trigger: "blur" }],
  amount: [{ validator: Denomination, required: true, trigger: "blur" }],
  minPoint: [{ validator: PositiveInteger, required: true, trigger: "blur" }],
};

//添加
const productCategoryId = ref(0)
const need = ref<any>([])
const needTwo = ref<any>([])
const id = ref(0)
const addToList = () => {
  if (treeValue.value.length == 0) {
    ElMessage.warning('请选择商品分类')
  } else {
    id.value = getChildrenList.value.find(item => item = treeValue.value[0])?.id!
    productCategoryId.value = getChildrenList.value.find(item => item = treeValue.value[0])?.children.find(item => item = treeValue.value[1])?.id!
    need.value.push({ id: id.value, parentCategoryName: treeValue.value[0], productCategoryName: treeValue.value[1], productCategoryId: productCategoryId.value })
    listValue.value.push(need.value)
  }
}
const delListValue = (index: number) => {
  listValue.value.splice(index, 1)
}

const treeValue = ref<ProductCategoryWithChildren[]>([])
const listValue = ref<string[]>([])
const treeProps = {
  children: 'children',
  label: 'name',
  value: 'name'
}

const keyword = ref('')

const getChildrenList = ref<ProductCategoryWithChildren[]>([])
const get = () => {
  getProductCategoryListWithChildren().then(res => {
    if (res.code === 200) {
      getChildrenList.value = res.data
      getChildrenList.value.forEach(item => {
        if (item.children.length == 0) {
          item.disabled = true
        }
      })
    }
  })
}
get()
const optionsType = [
  { label: '全场赠券', value: 0 },
  { label: '会员赠券', value: 1 },
  { label: '购物赠券', value: 2 },
  { label: '注册赠券', value: 3 },
]
const optionsPlatform = [
  { label: '全平台', value: 0 },
  { label: '移动平台', value: 1 },
  { label: 'PC平台', value: 2 },
]
const formRef = ref<FormInstance>();
const form = reactive<ConPonParams>({
  amount: null,
  code: '',
  count: 0,
  enableTime: '',
  endTime: '',
  id: 0,
  memberLevel: 0,
  minPoint: undefined,
  name: '',
  note: undefined,
  perLimit: 1,
  platform: 0,
  publishCount: undefined,
  receiveCount: 0,
  startTime: '',
  type: 0,
  useCount: 0,
  useType: 0,
  productCategoryRelationList: [],
  productRelationList: []
})
const router = useRouter()
const addUser = () => {
  ElMessageBox.confirm("是否提交数据", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      form.productCategoryRelationList = need.value
      addCoupon(form).then((res) => {
        if (res.code === 200) {
          ElMessage.success('添加成功')
          formRef.value?.resetFields();
          router.push('/sms/coupon')
        }
      });
    })
    .catch(() => {
    });
};
const submitFn = () => {
  formRef.value?.validate((ok: boolean) => {
    if (ok) {
      addUser()
    } else {
    }
  });
};
</script>
<style lang="less" scoped>
.box-card {
  margin: auto;
  padding: 50px;
  align-items: center;
  width: 700px;
}

.flex {
  padding: 20px;
  display: flex;
  padding-left: 100px;
  justify-content: left;
}
</style>
